
//#ifdef H5
import jweixin from "jweixin-module"
//#endif
import api from "./api"
import config from "./conf"

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

function getWechatCode(redirect_url) {
	let state = redirect_url.replace('?/#', '%3F/%23');
	
	///let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.AppId}&redirect_uri=${encodeURIComponent(redirect_url)}&&response_type=code&scope=snsapi_userinfo#wechat_redirect`
	
	let url = config.authUrl + '?scope=1&state=' + state;
	location.href = url;
}

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

function is_weixin() {
	
	//#ifdef H5
		let ua = navigator.userAgent.toLowerCase();
		let isWeixin = ua.indexOf('micromessenger') != -1;
		if (isWeixin) {
			return true;
		} else {
			return false;
		}
	//#endif
	return false
	
}

function checkPhone(v) {
	if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(v))) {
		return false
	} else {
		return true
	}
}

function checkIdNo(num) {
	if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
		return false;
	}
	return true
}

function idCarFomat(str) {
	if (str) {
		return str.replace(/(.{5}).*(.{4})/, "$1******$2")
	}
	return "无信息"

}

function mobileFomat(str) {
	if (null != str && str != undefined) {
		var pat = /(\d{3})\d*(\d{4})/;
		return str.replace(pat, '$1****$2');
	} else {
		return "未填写";
	}
}

/**
 * @param {Object} date
 * @param {Object} fmt yyyy-MM-dd hh:mm:ss || yyyy-MM-dd
 */
function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
}

function padLeftZero(str) {
    return ('00' + str).substr(str.length);
}
//获取近几天的时间
//day:表示相差天数
//type:0表示往后几天,1表示往前几天
//如day为2时,当前为2020-01-08  当type为0时返回2020-01-07 ,当type为1时返回2020-01-09
function getDay(day,type) {
	var today = new Date();
	var targetday_milliseconds="";
	if(type==0){
		targetday_milliseconds=today.getTime() - 1000*60*60*24*day;
	}else{
		targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
	}
	
	today.setTime(targetday_milliseconds); //注意，这行是关键代码
	var tYear = today.getFullYear();
	var tMonth = today.getMonth();
	var tDate = today.getDate();
	if((tMonth+1).toString().length == 1){
	 tMonth = "0" + (tMonth+1);
	}
	if((tDate+1).toString().length == 1){
	 tDate = "0" + tDate;
	}
	return tYear+"-"+tMonth+"-"+tDate;	
}
async function wxinit(callback) {
	if (is_weixin()) {
		var url = window.location.href;
		var sp = url.split("#");
		let res = await api.getWxConfig(sp[0]);
		jweixin.config(res.config);
		jweixin.ready(function() {
			console.log("success")
			if (typeof(callback) === 'function') {
				callback()
			}
		});
	}

}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

module.exports = {
	formatTime: formatTime,
	formatDate:formatDate,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	is_weixin: is_weixin,
	wx_init: wxinit,
	getWechatCode: getWechatCode,
	getQueryString: getQueryString,
	checkPhone: checkPhone,
	checkIdNo: checkIdNo,
	idCarFomat: idCarFomat,
	mobileFomat: mobileFomat,
	getDay:getDay
}
